<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="下单时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.placeOrderDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="原订单号" prop="backNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入原订单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="退款单号" prop="backNo">
        <el-input v-model="queryParams.backNo" placeholder="请输入退单单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="退款状态" prop="orderStatus">
        <el-select v-model="queryParams.refundStatus" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in refundStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="商户单号" prop="merchantOrderNo">
        <el-input v-model="queryParams.merchantOrderNo" placeholder="请输入商户单号" clearable @keyup.enter="handleQuery" />
      </el-form-item>


      <el-form-item label="付款时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.payDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="商户名称" prop="merchantName">
        <el-input v-model="queryParams.merchantName" placeholder="请输入商户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="店铺名称" prop="merchantShopName">
        <el-input v-model="queryParams.merchantShopName" placeholder="请输入店铺名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="售后类型" prop="orderStatus">
        <el-select v-model="queryParams.backType" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in backTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.applyOrderDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>



      <el-form-item label="发货时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.sendDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="商品编码" prop="code">
        <el-input v-model="queryParams.code" placeholder="请输入商品编码" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="买家信息" prop="buyUserInfo">
        <el-input v-model="queryParams.buyUserInfo" placeholder="请输入买家姓名/手机号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="售后状态" prop="backStatus">
        <el-select v-model="queryParams.backStatus" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in backStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="退款时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.backDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:backOrder:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="backOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="退单单号" align="center" prop="backNo" fixed width="200">
        <template #default="scope">
          <a style="cursor: pointer; color: #20a0ff; margin-right: 10px" @click="openOrderDetail(scope.row.id)" title="点击查看明细">
            {{ scope.row.backNo}}
          </a>
        </template>
      </el-table-column>
      <el-table-column label="原订单号" align="center" prop="orderNo" fixed width="200"/>
      <el-table-column label="商户单号" align="center" prop="merchantOrderNo" fixed width="200"/>
<!--      <el-table-column label="用户名称" align="center" prop="userName" width="200"/>-->
      <el-table-column label="商户名称" align="center" prop="merchantName" width="200"/>
      <el-table-column label="店铺名称" align="center" prop="merchantShopName" width="200"/>
      <el-table-column label="买家姓名" align="center" prop="buyUserName" width="150"/>
      <el-table-column label="买家电话" align="center" prop="buyUserPhone" width="150"/>
      <el-table-column label="原订单总价" align="center" prop="totalPrice" width="150"/>
      <el-table-column label="退款金额" align="center" prop="backPrice" width="150"/>
      <el-table-column label="商品编码" align="center" prop="code" min-width="150" class="list-container">
        <template #default="scope">
          <span class="list-item" :title="scope.row.code">{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款类型" align="center" prop="backType" width="150">
        <template #default="scope">
          <span v-if="scope.row.backType == 1">仅退款</span>
          <span v-if="scope.row.backType == 2">退款退货</span>
        </template>
      </el-table-column>
      <el-table-column label="售后状态" align="center" prop="backStatusStr" width="150"/>

      <el-table-column label="下单时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款时间" align="center" prop="payTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货时间" align="center" prop="shipTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.shipTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.applyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退款时间" align="center" prop="backTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.backTime) }}</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="150">
        <template #default="scope">
          <el-button link type="primary" @click="openOrderDetail(scope.row.id)">详情</el-button>

<!--          <el-button link type="primary" @click="handleConfig(scope.row.id, scope.row.orderNo, 'confirm')"-->
<!--                     v-if="scope.row.backStatus === 0">确认退单</el-button>-->
          <el-button link type="primary" @click="handleConfig(scope.row.id, scope.row.orderNo, 'cancel')"
                     v-if="scope.row.backStatus === 0  && !isAdmin">取消退单</el-button>
<!--          <el-button link type="primary" @click="handleConfig(scope.row.id, scope.row.orderNo, 'finish')"-->
<!--                     v-if="scope.row.backStatus === 0  && isAdmin ">完成退单</el-button>-->
          <el-button link type="primary" @click="handleConfig(scope.row.id, scope.row.orderNo, 'cancel')"
                     v-if="scope.row.backStatus === 0  && isAdmin ">拒绝退单</el-button>
          <el-button link type="primary" @click="handleApplyRefund(scope.row)"
                     v-if="scope.row.backStatus === 0  && isAdmin ">确认退单</el-button>
        </template>
      </el-table-column>
<!--
      <el-table-column label="操作" >
        <template #default="scope">
          <el-divider direction="vertical"></el-divider>
          <el-dropdown >
              <span class="el-dropdown-link">更多
                    <el-icon class="el-icon&#45;&#45;right"><arrow-down /></el-icon>
              </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-if="scope.row.backStatus === 0">
                  <a style="cursor: pointer; margin-right: 10px" @click="handleConfig(scope.row.id, scope.row.orderNo,'confirm')">确认退单</a>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.backStatus === 0">
                  <a style="cursor: pointer; margin-right: 10px" @click="handleConfig(scope.row.id, scope.row.orderNo,'cancel')">取消退单</a>
                </el-dropdown-item>
                <el-dropdown-item v-if="scope.row.backStatus === 1">
                  <a style="cursor: pointer; margin-right: 10px" @click="handleConfig(scope.row.id, scope.row.orderNo,'finish')">完成退单</a>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
-->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- Detail 组件 -->
    <Detail ref="detailRef" />

    <el-dialog :title="title" v-model="openRefundOrder" width="600px" append-to-body>
      <el-form ref="openRefundOrderRef" :model="form" label-width="100px">
        <el-form-item label="订单号" prop="orderNo">
          <el-input v-model="form.orderNo" placeholder="请输入订单号" disabled />
        </el-form-item>
        <el-form-item label="退单类型">
          <el-radio-group v-model="form.backType" prop="backType">
            <el-radio label="1">仅退款</el-radio>
            <el-radio label="2">退款退货</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="退款原因">
          <el-input v-model="form.backReasonName" placeholder="请输入退款金额" disabled />
        </el-form-item>
        <el-form-item label="订单退款金额" prop="totalPrice">
          <el-input v-model="form.totalPrice" placeholder="请输入订单退款金额" disabled />
        </el-form-item>
        <el-form-item label="运费退款金额" prop="freightPrice">
          <el-input v-model="form.freightPrice" placeholder="请输入运费退款金额" disabled />
        </el-form-item>
        <el-form-item label="退款备注" prop="backRemark">
          <el-input v-model="form.backRemark" type="textarea" placeholder="请输入退款备注" disabled/>
        </el-form-item>
<!--        <el-form-item label="图片" prop="img">
          <template #default="scope">
            <el-image
                @click.stop
                style="width: 100px; height: 100px"
                :key="scope.row.id"
                :src="scope.row.goodsCoverImg"
                :preview-teleported="true"
                :preview-src-list="[scope.row.goodsCoverImg]">
            </el-image>
          </template>
        </el-form-item>
-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfigRefund('finish')">确 定</el-button>
          <el-button @click="openRefundOrderCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BackOrder">
import { listBackOrder, getBackOrder, delBackOrder, addBackOrder, updateBackOrder, orderOperate } from "@/api/business/backOrder";
import Detail from './detail.vue';
import { getIsAdmin } from "@/api/system/user";
import { getIsManage } from "@/api/system/user";

const { proxy } = getCurrentInstance();

const backOrderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isAdmin = ref(true);//是单条还是多条
const openRefundOrder = ref(false);

const refundStatusOptions = ref([
  {
    value: '',
    label: '全部'
  }, {
    value: 0,
    label: '退款中'
  }, {
    value: 1,
    label: '退款成功'
  }
]);
const backTypeOptions = ref([
  {
    value: '',
    label: '全部'
  }, {
    value: 1,
    label: '仅退款'
  }, {
    value: 2,
    label: '退款退货'
  }
]);
const backStatusOptions = ref([
  {
    value: '',
    label: '全部'
  }, {
    value: 0,
    label: '待确认'
  }, {
    value: 1,
    label: '已确认'
  }, {
    value: 2,
    label: '已完成'
  }, {
    value: 3,
    label: '已取消'
  }
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    backNo: null,
    orderId: null,
    orderNo: null,
    userId: null,
    userName: null,
    merchantId: null,
    merchantName: null,
    merchantShopId: null,
    merchantShopName: null,
    buyUserName: null,
    buyUserPhone: null,
    totalPrice: null,
    backPrice: null,
    backType: null,
    statusStr: null,
    backStatus: null,
    backStatusStr: null,
    backTime: null,
    shipTime: null,
    placeOrderDateRange:null,
    refundStatus: null,
    payDateRange:null,
    sendDateRange:null,
    code:null,
    backDateRange:null,
    applyOrderDateRange:null,
    merchantOrderNo: null
  },
  rules: {
  },

  searchParams: {
    id: null,
    orderNo : null,
    menuCode: null
  },
});
const detailRef = ref(null);
const { queryParams, form, rules, searchParams } = toRefs(data);

/** 查询退单信息列表 */
function getList() {
  loading.value = true;
  listBackOrder(queryParams.value).then(response => {
    backOrderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    backNo: null,
    orderId: null,
    orderNo: null,
    userId: null,
    userName: null,
    merchantId: null,
    merchantName: null,
    merchantShopId: null,
    merchantShopName: null,
    buyUserName: null,
    buyUserPhone: null,
    totalPrice: null,
    backPrice: null,
    backType: null,
    statusStr: null,
    backStatus: null,
    backStatusStr: null,
    backTime: null,
    shipTime: null,
    delFlag: null,
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    merchantOrderNo : null
  };
  proxy.resetForm("backOrderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加退单信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getBackOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改退单信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["backOrderRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBackOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBackOrder(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除退单信息编号为"' + _ids + '"的数据项？').then(function() {
    return delBackOrder(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/backOrder/export', {
    ...queryParams.value
  }, `退单列表_${new Date().getTime()}.xlsx`)
}


function handleConfig (id, orderNo, menuCode){

  searchParams.value.id = id;
  searchParams.value.orderNo = orderNo;
  searchParams.value.menuCode = menuCode;
  proxy.$modal.confirm('是否确认？').then(function() {
    return orderOperate(searchParams.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});

}

function handleConfigRefund (menuCode){

  searchParams.value.menuCode = menuCode;
  proxy.$modal.confirm('是否确认完成退单？').then(function() {
    openRefundOrder.value = false;
    return orderOperate(searchParams.value);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => {});

}


function handleApplyRefund(row) {

  searchParams.value.id = row.id;
  searchParams.value.orderNo = row.orderNo;

  getBackOrder(row.id).then(response => {
    form.value = response.data;
    openRefundOrder.value = true;
    title.value = "操作";
  });
}

// 取消按钮
function openRefundOrderCancel() {
  openRefundOrder.value = false;
  reset();
}


// 详情
function openOrderDetail(id) {
  if (detailRef.value) detailRef.value.init(id);
}

function init() {
  // getIsAdmin().then(response => {
  getIsManage().then(response => {
    console.log("----isAdmin.value-----" , response)
    //为false时，代表是子商户
    isAdmin.value = response;
  });
}

init();
getList();
</script>

<style>
.list-container {
  width: 200px; /* 设定一个宽度 */
}

.list-item {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的内容 */
  text-overflow: ellipsis; /* 显示省略号 */
}
</style>